#include "tableinfo.h"
#include "abstractstorage.h"
#include "defines.h"

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QVariant>
#include <QStringList>
#include <QDebug>



TableInfo::TableInfo(const QString &tableName, const QSqlDatabase &db) : m_valid(false)
{
    if( db.driverName().compare("QSQLITE") == 0 )
        getInfoFromSqlite3(tableName,db);
}

TableInfo::TableInfo(AbstractContainer *columns)
{
    m_columns = *columns;
    m_valid = true;
}

void TableInfo::getInfoFromSqlite3(const QString &tableName, const QSqlDatabase &db)
{
    QSqlQuery query(db);
    if( query.exec("SELECT sql FROM sqlite_master where name = '" + tableName +"'") && query.first()) {
        QString sql =  query.record().value(0).toString();
        int left,right;
        left = sql.indexOf('(')+1;
        right = sql.lastIndexOf(')')-1;

        m_valid = parseColumnsFromSql( sql.mid( left, right-left+1 ) );
    }
}

bool TableInfo::parseColumnsFromSql(const QString &sqlColumns)
{
    QStringList columns = sqlColumns.trimmed().split(',');
    for( int i = 0; i < columns.size(); i++ ) {
        QString column = columns.at(i).trimmed();
        int pos1 = column.indexOf(' ');
        QString columnName = column.left(pos1);
        columnName.replace('[',"");columnName.replace(']',"");
        pos1 = column.indexOf(QRegExp("\\w"),pos1+1);
        int pos2 = column.indexOf(QRegExp("[\\(\\s]"),pos1+1);
        int length = pos2>0?pos2-pos1:-1;

        QString type = column.mid(pos1,length);
        bool primary = pos2>0?column.indexOf("primary", pos2, Qt::CaseInsensitive)>0:false;

        int columnLength = 0;
        pos1 = column.indexOf('(');
        pos2 = column.indexOf(')');
        if(pos2 > 0 && pos1 > 0)
            columnLength = column.mid(pos1+1,pos2-pos1-1).trimmed().toInt();

        AbstractStorage col;
        col.setProperty(XML_COLUMNNAME, columnName);
        col.setProperty(XML_COLUMNTYPE, type);
        col.setProperty(XML_ISPRIMARYKEY, primary);
        col.setProperty(XML_COLUMNLENGTH, columnLength);
        m_columns.append(&col);
    }
    return true;
}

QString TableInfo::columnName(int col)
{
    QString res;
    if(m_valid && col < m_columns.size())
        res = m_columns.at(col)->property(XML_COLUMNNAME).toString();
    return res;
}

QString TableInfo::columnType(int col)
{
    QString res;
    if(m_valid && col < m_columns.size())
        res = m_columns.at(col)->property(XML_COLUMNTYPE).toString();    
    return res;
}

bool TableInfo::isEqual(AbstractContainer *)
{
    bool res = true;
    //TODO: check field types and names
    return res;
}
